/* eslint-disable react-hooks/exhaustive-deps */
/* eslint-disable @next/next/no-img-element */
import * as React from "react";
import { IArticle, ILike, IUser } from "../../types";
import styles from "./style.module.scss";
import * as userService from "../../services/user.service";
import Link from "next/link";

interface Props {
  user: IUser;
}

export default function Follows(props: Props) {
  const [rows, setRows] = React.useState<(ILike | IArticle)[]>([]);
  const [type, setType] = React.useState<number[]>([]); //1为IArticle，2为ILike

  const getData = React.useCallback(async () => {
    const follows = await userService.follows(props.user._id);
    let a: (ILike | IArticle)[] = [];
    for (let i = 0; i < follows.rows.length; i++) {
      const likerows = await userService.likes(follows.rows[i].toUserId);
      const articlerows = await userService.articles(follows.rows[i].toUserId);
      a.push(...likerows.rows);
      a.push(...articlerows.rows);
      setType(
        type
          .concat(new Array(likerows.rows.length).fill(2))
          .concat(new Array(articlerows.rows.length).fill(1))
      );
    }
    a.sort((a: ILike | IArticle, b: ILike | IArticle) => {
      return new Date(b.time).valueOf() - new Date(a.time).valueOf();
    });
    setRows(a);
  }, [props.user._id]);

  React.useEffect(() => {
    getData();
  }, [getData]);

  return (
    <div className={styles.inner}>
      {rows.map((item, index) => {
        if (type[index] === 1) {
          return (
            <div key={index} className={styles.item}>
              <div className={styles.in}>
                <Link href={"/user/" + item.user[0]._id} passHref>
                  <img
                    src={`/api/article/download/${item.user[0].avatar}`}
                    alt=""
                  />
                </Link>
                {item.user[0].nickname} 发布了文章 《{item.title}》
              </div>

              <div className={styles.time}>
                {new Date(item.time).toLocaleDateString() +
                  " " +
                  new Date(item.time).toLocaleTimeString()}
              </div>
            </div>
          );
        } else {
          return (
            <div key={index} className={styles.item}>
              <div className={styles.in}>
                <Link href={"/user/" + item.user[0]._id} passHref>
                  <img
                    src={`/api/article/download/${item.user[0].avatar}`}
                    alt=""
                    style={{ cursor: "pointer" }}
                  />
                </Link>
                {item.user[0].nickname} 点赞了文章 《{item.title}》
              </div>

              <div className={styles.time}>
                {new Date(item.time).toLocaleDateString() +
                  " " +
                  new Date(item.time).toLocaleTimeString()}
              </div>
            </div>
          );
        }
      })}
    </div>
  );
}
